package com.echo.yixiaowu.feature.components

import android.app.Activity
import android.content.ContentResolver
import android.content.pm.ActivityInfo
import android.net.Uri
import android.os.Bundle
import androidx.activity.compose.BackHandler
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.session.MediaController
import androidx.media3.ui.PlayerView
import androidx.navigation.NavHostController
import com.echo.yixiaowu.R
import com.echo.yixiaowu.data.model.player.CardDetailItemData
import com.echo.yixiaowu.feature.player.MediaPageIntent
import com.echo.yixiaowu.feature.player.MediaViewModel
import com.echo.yixiaowu.util.NavLock
import com.echo.yixiaowu.util.hideSystemUI
import com.echo.yixiaowu.util.showSystemUI
import kotlinx.coroutines.launch

@Composable
fun VideoPlayerContainer(
    itemData: CardDetailItemData.VideoItem,
    viewModel: MediaViewModel,
    isFullScreen: Boolean,
    activity: Activity?,
    navController: NavHostController,
    mediaController: MediaController?,
    content: @Composable (player: @Composable (Modifier) -> Unit) -> Unit
) {
    val scope = rememberCoroutineScope()

    fun buildMediaItem(): MediaItem {
        val uri = Uri.Builder().scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
            .path(R.raw.test1.toString()).build()
        val data = Bundle().apply {
            putString("itemId", itemData.baseData.id)
            putString("itemType", itemData.baseData.type.toString())
        }
        val mediaMetadata =
            MediaMetadata.Builder().setTitle(itemData.baseData.title).setExtras(data).build()

        return MediaItem.Builder().setUri((uri)).setMediaId(itemData.baseData.id)
            .setMediaMetadata(mediaMetadata).build()
    }

    LaunchedEffect(mediaController, itemData) {
        mediaController?.let {
            val mediaItem = buildMediaItem()
            viewModel.playItem(mediaItem)
        }
    }

    LaunchedEffect(isFullScreen) {
        if (isFullScreen) {
            // 进入全屏时，强制横屏并隐藏SystemUI
            //todo 可以加入是否竖屏视频判断
            activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            activity?.hideSystemUI()
        } else {
            // 退出全屏时，强制竖屏并显示SystemUI
            activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
            activity?.showSystemUI()
        }
    }

    BackHandler {
        if (isFullScreen) {
            viewModel.processIntent(
                MediaPageIntent.ClickMediaFullScreen(
                    true, viewModel.mediaUiState.value.originalVideoHeight
                )
            )
        } else {
            mediaController?.stop()
            mediaController?.playWhenReady = false
            scope.launch {
                mediaController?.clearMediaItems()
                navController.popBackStack()
                NavLock.unlock()
            }
        }
    }
    content { modifier ->
        AndroidView(modifier = modifier, factory = { context ->
            PlayerView(context).apply {
                // 禁用自带控制器
                useController = false
            }
        }, update = { playerView ->
            playerView.player = mediaController
        })
    }
}